import request from "@/utils/request";
import { defineStore } from "pinia";
import type { TregForm } from "@/components/registerForm/index.vue";
import type { TloginForm } from "@/components/LoginForm/index.vue";
import { setToken, removeToken } from "@/utils/storage";
import { ElMessage } from "element-plus";

export const userStore = defineStore("user", {
  state: () => {
    return {
      token: "",
      userInfo: {} as {
        id?: number;
        username?: string;
        email?: string;
        profilePhotoUrl?: string;
      },
    };
  },
  actions: {
    /**
     * 注册
     * @param regForm
     */
    async registerUser(regForm: TregForm) {
      const res = await request.post("/user/register", regForm);
      if (res.data.message === "注册成功") ElMessage.success("注册成功！");
    },

    /**
     * 登录
     * @param loginForm
     */
    async userLogin(loginForm: TloginForm) {
      const res = await request.post("user/login", loginForm);
      if (res.data.message == "登录成功") {
        ElMessage.success("登录成功！");
        this.token = res.data.data.token;
        this.userInfo = res.data.data;
        setToken(res.data.data.token); //本地持久化
      } else {
        ElMessage.error(res.data.message);
      }
    },
    /**
     * 登出
     */
    userLogout() {
      this.token = "";
      this.userInfo = {};
      removeToken(); //移除本地
    },

    /**
     * 校验token,获取信息
     */
    async validToken() {
      const res = await request.post("user/token");
      if (res.data.code === 0) {
        this.token = res.data.data.token;
        this.userInfo = res.data.data;
        setToken(res.data.data.token); //本地持久化
      } else {
        ElMessage.error(res.data.message);
      }
    },
  },
});
